#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int minTimeToReach(vector<vector<int>>& moveTime) {
    int n = moveTime.size(), m = moveTime[0].size();
    vector<vector<int>> dist(n, vector<int>(m, INT_MAX));
    dist[0][0] = 0;
    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq;
    pq.emplace(0, 0, 0);
    while (true)
    {
        auto [d, x, y] = pq.top();
        pq.pop();
        if (x == n - 1 && y == m - 1)
            return d;

        if (d > dist[x][y])
            continue;

        for (int i = 0; i < 4; i++)
        {
            int a = dx[i] + x;
            int b = dy[i] + y;

            if (a < 0 || b < 0 || a >= n || b >= m)
                continue;
            int ndis = max(d, moveTime[a][b]) + 1;
            if (ndis < dist[a][b])
            {
                dist[a][b] = ndis;
                pq.emplace(ndis, a, b);
            }
        }
    }
}